<script setup lang="ts">
  import { onMounted, ref } from "vue";
  import { useDictStore } from "@/stores";

  const dictStore = useDictStore();
  const modalVisible = ref(false);
  const dictGroups = ref<any>([]);
  const dictGroup = ref<any>({});
  const emit = defineEmits(["select"]);

  onMounted(() => {
    fetchList();
  });

  async function fetchList() {
    dictGroups.value = await dictStore.getDictGroupList();
    handleSelect(dictGroups.value[0]);
  }

  function handleAdd() {
    dictGroup.value = {};
    modalVisible.value = true;
  }

  function handleEdit(record: any) {
    dictGroup.value = record;
    modalVisible.value = true;
  }

  async function handleRemove(record: any) {
    await dictStore.deleteDictGroup({ id: record.id });
    dictGroups.value = dictGroups.value.filter((item: any) => item.id !== record.id);
  }

  async function handleSave() {
    await dictStore.saveDictGroup({ ...dictGroup.value });
    await fetchList();
    modalVisible.value = false;
  }

  function handleSelect(record: any) {
    dictGroup.value = record;
    emit("select", record);
  }
</script>

<template>
  <a-card :bordered="false">
    <a-button type="primary" size="small" style="margin-bottom: 16px" @click="handleAdd">新增</a-button>
    <div class="list" v-if="dictGroups.length > 0">
      <template v-for="item in dictGroups">
        <a-dropdown trigger="contextMenu" alignPoint>
          <div class="list-item" :class="{ active: dictGroup.id === item.id }" @click="handleSelect(item)">{{ item.name }}</div>
          <template #content>
            <a-doption @click="handleEdit(item)">编辑</a-doption>
            <a-doption @click="handleRemove(item)">移除</a-doption>
          </template>
        </a-dropdown>
      </template>
    </div>
    <a-empty v-else></a-empty>
  </a-card>
  <a-modal :visible="modalVisible" title="字典资料" @cancel="modalVisible = false" @ok="handleSave">
    <a-form :model="{}" auto-label-width>
      <a-form-item label="分组名称">
        <a-input placeholder="请输入分组名称" v-model="dictGroup.name"></a-input>
      </a-form-item>
      <a-form-item label="分组编码" style="margin-bottom: 0">
        <a-input placeholder="请输入分组编码" v-model="dictGroup.code"></a-input>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<style lang="scss" scoped>
  .list {
    &-item {
      line-height: 40px;
      cursor: pointer;
      padding: 0 8px;
      border-radius: 4px;

      &.active {
        background-color: #f5f5f5;
      }
    }
  }
</style>
